package com.kingyun.gpsinspection.purificationservice.services.iam.innerservice.scyx.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.accessory.EntityPropertyVoMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.accessory.EntityTypePropertyVoMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.accessory.EntityVoMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.scyx.DeviceSumTempDevitemMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.scyx.DeviceSumTempDevlistMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.scyx.DeviceSumTempInfoMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.iam.scyx.DeviceSumTempSubtypeMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.accessory.EntityPropertyVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.accessory.EntityTypePropertyVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.accessory.EntityVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.iam.scyx.*;
import com.kingyun.gpsinspection.purificationservice.facade.service.iam.scyx.DeviceSumTempInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ${yangsy} on 2017/3/16.
 */
public class DeviceSumTempInfoServiceImpl implements DeviceSumTempInfoService {
    private static Logger logger = LoggerFactory.getLogger(DeviceSumTempInfoServiceImpl.class);
    @Autowired
    private DeviceSumTempSubtypeMapper deviceSumTempSubtypeMapper;
    @Autowired
    private DeviceSumTempDevlistMapper deviceSumTempDevlistMapper;
    @Autowired
    private DeviceSumTempDevitemMapper deviceSumTempDevitemMapper;
    @Autowired
    private DeviceSumTempInfoMapper deviceSumTempInfoMapper;
    @Autowired
    private EntityVoMapper entityVoMapper;
    @Autowired
    private EntityPropertyVoMapper entityPropertyVoMapper;
    @Autowired
    private EntityTypePropertyVoMapper entityTypePropertyVoMapper;

    @Transactional(propagation = Propagation.REQUIRED)
    public int deleteByPrimaryKey(String deviceSumTempId, boolean isDeleteAll) {
        Map<String, Object> map = new HashMap<>();
        map.put("deviceSumTempId", deviceSumTempId);
        map.put("isDeleteAll", isDeleteAll);
        return deviceSumTempInfoMapper.deleteByPrimaryKey(map);
    }

    @Override
    public DeviceSumTempInfo selectByPrimaryKey(String deviceSumTempId) {
        return deviceSumTempInfoMapper.selectByPrimaryKey(deviceSumTempId);
    }

    @Override
    public JSONObject list(DeviceSumTempInfo deviceSumTempInfo) {
        JSONObject jsonObject = new JSONObject();
        deviceSumTempInfo.setLimit(deviceSumTempInfo.getLimit() == null ? 10 : deviceSumTempInfo.getLimit());
        deviceSumTempInfo.setOffset(deviceSumTempInfo.getOffset() == null ? 0 : deviceSumTempInfo.getOffset());
        jsonObject.put("total", deviceSumTempInfoMapper.queryCount(deviceSumTempInfo));
        jsonObject.put("rows", JSON.toJSON(deviceSumTempInfoMapper.queryList(deviceSumTempInfo)));
        return jsonObject;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int insertSelective(DeviceSumTempInfo record, String submitStr) {
        int resultCount = 0;
        //  首先插入设备台账模板基本信息
        resultCount += deviceSumTempInfoMapper.insertSelective(record);
        //  插入模板表 （ 子类型 + 设备 + 设备采集项
        resultCount += insertDSTConfigInfo(record, submitStr);
        return resultCount;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int updateByPrimaryKeySelective(DeviceSumTempInfo record, String submitStr) {
        int resultCount = 0;
        //  先更新台账模板基本信息
        resultCount += deviceSumTempInfoMapper.updateByPrimaryKeySelective(record);
        //  删除 有关台账模板的所有数据(包括子类型，设备列表，设备采集项
        resultCount += this.deleteByPrimaryKey(record.getDeviceSumTempId(), false);
        //  更新台账配置信息
        resultCount += insertDSTConfigInfo(record, submitStr);
        return resultCount;
    }

/*    @Override
    public List<DeviceSumTempInfoVo> getDSTConfigInfo(String deviceSumTempId) {
        List<DeviceSumTempInfoVo> list = null;
        if (deviceSumTempId == null || "".equals(deviceSumTempId)) {
            return null;
        }
        try {
            list = deviceSumTempInfoMapper.getDSTConfigInfo(deviceSumTempId);
        } catch (Exception e) {
            logger.error("获取台账模板子类型信息异常:" + e.getMessage());
        }
        return list;
    }*/

    /**
     * 更新台账模板配置信息
     *
     * @param deviceSumTempInfo 台账模板基本信息
     * @param submitStr         台账模板子类型信息
     * @return
     */
    protected int insertDSTConfigInfo(DeviceSumTempInfo deviceSumTempInfo, String submitStr) {
        int resultCount = 0;
        List<DeviceSumTempInfoVo> list = JSON.parseArray(submitStr, DeviceSumTempInfoVo.class);
        if (list == null || list.size() < 0) {
            return resultCount;
        }
        //  循环遍历子类型信息
        for (DeviceSumTempInfoVo vo : list) {
            //  1. 更新子类型表数据
            DeviceSumTempSubtype deviceSumTempSubtype = new DeviceSumTempSubtype();
            //  主键
            deviceSumTempSubtype.setDeviceSumSubtypeId(UniqueUtil.uuid());
            //  设备台账模板id
            deviceSumTempSubtype.setDeviceSumTempId(deviceSumTempInfo.getDeviceSumTempId());
            //  子类型名
            deviceSumTempSubtype.setSubtypeName(vo.getSubtypeName());
            //  do insert
            resultCount += deviceSumTempSubtypeMapper.insertSelective(deviceSumTempSubtype);
            //   2.更新设备列表数据
            DeviceSumTempDevlist deviceSumTempDevlist = new DeviceSumTempDevlist();
            //  主键
            deviceSumTempDevlist.setDevlistTempId(UniqueUtil.uuid());
            //  设备台账模板id
            deviceSumTempDevlist.setDeviceSumTempId(deviceSumTempInfo.getDeviceSumTempId());
            // 设置 生产实体类型
            deviceSumTempDevlist.setDd(vo.getEntityTypeId());
            //  设置子类型id
            deviceSumTempDevlist.setDeviceSumSubtypeId(deviceSumTempSubtype.getDeviceSumSubtypeId());
            //  do inset
            resultCount += deviceSumTempDevlistMapper.insertSelective(deviceSumTempDevlist);
            //  3.更新设备采集项数据
            String[] propertys = vo.getProperty().split(",");// 截取数据，用逗号隔开的
            int propertyLen = propertys.length;
            for (int j = 0; j < propertyLen; j++) {
                DeviceSumTempDevitem deviceSumTempDevitem = new DeviceSumTempDevitem();
                //  主键
                deviceSumTempDevitem.setDeviceSumDevitemId(UniqueUtil.uuid());
                //  设备id
                deviceSumTempDevitem.setDevlistTempId(deviceSumTempDevlist.getDevlistTempId());
                //  设备特性id
                deviceSumTempDevitem.setDevPropertyId(propertys[j]);
                //  序号
                deviceSumTempDevitem.setSortNum(j+1);
                //  do insert
                deviceSumTempDevitemMapper.insertSelective(deviceSumTempDevitem);
            }
        }
        return resultCount;
    }

    /**
     * 获取生产实体类型特性
     *
     * @param entityTypePropertyVo
     * @return
     */
    protected List<EntityTypePropertyVo> getEntityTypePropertys(EntityTypePropertyVo entityTypePropertyVo, String devListTempId) {
        List<EntityTypePropertyVo> list = null;
        try {
            if (entityTypePropertyVo == null) {
                //  根据设备项 查询数据
                list = entityTypePropertyVoMapper.queryList2(devListTempId);
            } else {
                //  根据生产实体类型Id
                list = entityTypePropertyVoMapper.queryList(entityTypePropertyVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询生产实体类型特性异常:" + e.getMessage());
        }
        return list;
    }

    @Override
    public Object getDeviceTitles(DeviceSumTempInfoVo deviceSumTempInfoVo) {
        List<EntityTypePropertyVo> list = this.pottingTitle(deviceSumTempInfoVo);
        if (list == null || list.size() < 0) return null;
        List<Map<String, String>> mapList = new ArrayList<>();
        for (EntityTypePropertyVo entityTypePropertyVo : list) {
            Map<String, String> map = new HashMap<>();
            map.put("title", entityTypePropertyVo.getPropertyName());
            map.put("field", entityTypePropertyVo.getDevicePropertyId());
            mapList.add(map);
        }
        return JSON.toJSON(mapList);
    }

    @Override
    public JSONObject getDeviceContents(DeviceSumTempInfoVo deviceSumTempInfoVo) {
        //  查询当前子类型台账内容信息
        JSONObject jsonObject = new JSONObject();
        deviceSumTempInfoVo.setLimit(deviceSumTempInfoVo.getLimit() == null ? 10 : deviceSumTempInfoVo.getLimit());
        deviceSumTempInfoVo.setOffset(deviceSumTempInfoVo.getOffset() == null ? 0 : deviceSumTempInfoVo.getOffset());
        //  查询当前生产实体类型 下面的 所有生产实体
        List<EntityVo> entityVoList = this.getEntity(deviceSumTempInfoVo, true);
        if (entityVoList == null || entityVoList.size() < 0) {
            return null;
        }
        List<Map<String, String>> operationList = new ArrayList<>();
        //  生产实体大小
        int entityVoListLen = entityVoList.size();
        //  生产实体特性信息
        Map<String, Object> entityPropertyValue = getEntityPropertyValue(deviceSumTempInfoVo);
        for (int i = 0; i < entityVoListLen; i++) {
            EntityVo entityVo = entityVoList.get(i);
            //  表头信息
            List<EntityTypePropertyVo> entityTypePropertyVoList = this.pottingTitle(deviceSumTempInfoVo);
            if (entityTypePropertyVoList == null || entityTypePropertyVoList.size() < 0) {
                return null;
            }
            Map<String, String> retMap = new HashMap<>();
            int entityTypePropertyVoListLen = entityTypePropertyVoList.size();
            for (int j = 0; j < entityTypePropertyVoListLen; j++) {
                EntityTypePropertyVo entityTypePropertyVo = entityTypePropertyVoList.get(j);
                //  实体特性
                String propertyValue = "";
                //  单元格第一列是设备名称 需要特殊处理
                if (entityTypePropertyVo.getDevicePropertyId().equals("entityId")) {
                    propertyValue = entityVo.getDeviceInfoVo().getDeviceName();
                } else {
                    String datasourseType = entityTypePropertyVo.getDatasoursetype();
                    String columnCode = entityTypePropertyVo.getColumnCode();
                    //  从生产实体特性里面获取数据
                    if (datasourseType == null || "".equals(datasourseType)) {
                        Object object = entityPropertyValue.get(entityVo.getEntityId() + entityTypePropertyVo.getDevicePropertyId());
                        propertyValue = (String) object;
                    } else {
                        //  从设备基本信息表里面获取数据
                        propertyValue = ReflectUtil.reflectGetValue(entityVo, datasourseType, columnCode);
                    }
                }
                if(propertyValue == null  || "".equals(propertyValue)) {
                    propertyValue = null;
                }
                retMap.put(entityTypePropertyVo.getDevicePropertyId(), propertyValue);
            }
            operationList.add(retMap);
        }
        EntityVo entityVo = new EntityVo();
        Map<String, String> map = mapValue(deviceSumTempInfoVo);
        entityVo.setEntityTypeId(map.get("entityTypeId"));
        entityVo.setParentOrgId(map.get("orgId"));
        jsonObject.put("total", entityVoMapper.queryCount(entityVo));
        jsonObject.put("rows", JSON.toJSON((operationList)));
        return jsonObject;
    }

    @Override
    public DeviceSumTempInfo selectSubTypeInfo(String deviceSumTempId) {
        return deviceSumTempInfoMapper.selectSubTypeInfo(deviceSumTempId);
    }

    /**
     * 封装台账表头数据
     * @param deviceSumTempInfoVo
     * @return
     */
    protected List<EntityTypePropertyVo> pottingTitle(DeviceSumTempInfoVo deviceSumTempInfoVo) {
        List<EntityTypePropertyVo> list = new ArrayList<>();
        if (deviceSumTempInfoVo == null) {
            return list;
        }
        try {
            //  封装当前子类型台账表头信息
            EntityTypePropertyVo entityTypePropertyVo = new EntityTypePropertyVo();
            entityTypePropertyVo.setEntityTypeId(deviceSumTempInfoVo.getEntityTypeId());
            list = this.getEntityTypePropertys(null,deviceSumTempInfoVo.getDevlistTempId());
            entityTypePropertyVo = new EntityTypePropertyVo();
            entityTypePropertyVo.setDevicePropertyId("entityId");
            entityTypePropertyVo.setPropertyName("设备名称");
            list.add(0, entityTypePropertyVo);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("获取生产生产类型特性数据异常:" + e.getMessage());
        }
        return list;
    }

    /**
     * 获取生产实体数据
     *
     * @param deviceSumTempInfoVo
     * @param isPaging            是否需要分页
     * @return
     */
    protected List<EntityVo> getEntity(DeviceSumTempInfoVo deviceSumTempInfoVo, boolean isPaging) {
        deviceSumTempInfoMapper.selectByPrimaryKey(deviceSumTempInfoVo.getDevlistTempId());
        EntityVo entityVo = new EntityVo();
        Map<String, String> map = mapValue(deviceSumTempInfoVo);
        entityVo.setEntityTypeId(map.get("entityTypeId"));
        entityVo.setParentOrgId(map.get("orgId"));
        if (isPaging) {
            return entityVoMapper.queryListNotPaging(entityVo);
        }
        return entityVoMapper.queryList(entityVo);
    }

    /**
     * 获取生产实体特性值数据
     *
     * @param deviceSumTempInfoVo
     * @return
     */
    protected Map<String, Object> getEntityPropertyValue(DeviceSumTempInfoVo deviceSumTempInfoVo) {
        Map<String, Object> map = new HashMap<>();
        if (deviceSumTempInfoVo == null) {
            return map;
        }
        EntityPropertyVo entityPropertyVo = new EntityPropertyVo();
        entityPropertyVo.setEntityTypeId(deviceSumTempInfoVo.getEntityTypeId());
        List<EntityPropertyVo> list = entityPropertyVoMapper.queryList(entityPropertyVo);
        if (list == null || list.size() < 0) {
            return map;
        }
        //  循环遍历 生产实体 特性数据
        for (EntityPropertyVo e : list) {
            //  生产实体Id  + 生产实体特性id 作为key
            String key = e.getEntityId() + e.getEntpPropertyId();
            map.put(key, e.getPropertyValue());
        }
        return map;
    }

    protected Map<String, String> mapValue(DeviceSumTempInfoVo deviceSumTempInfoVo) {
        Map<String, String> map = new HashMap<>();
        if (deviceSumTempInfoVo == null) {
            return map;
        }
        DeviceSumTempInfo deviceSumTempInfo = deviceSumTempInfoMapper.selectBydevListTempId(deviceSumTempInfoVo.getDevlistTempId());
        if (deviceSumTempInfo == null) {
            return map;
        }
        map.put("entityTypeId", deviceSumTempInfoVo.getEntityTypeId());
        map.put("orgId", deviceSumTempInfo.getOrgId());
        return map;
    }
}
